package com.weilive.core.utils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class LoadAverage {

	private static final DecimalFormat df = new DecimalFormat("#.00000");
	
	public static class Load {
		public final long process_time;
		public final long process_date = System.currentTimeMillis();
		public Load(long process_time) { this.process_time = process_time; }
	}

	private final long time_interal;
	private long count = 0;
	private double total_ms = 0;
	private List<Load> loads = new ArrayList<Load>();

	public LoadAverage(long time_interal) {
		this.time_interal = time_interal > 1000 ? time_interal : 1000;
	}

	public void add(Load new_load) {
		synchronized(this) {
			// 清除超时的load
			long expired_time = System.currentTimeMillis() - time_interal;
			for (int i = 0; i < loads.size(); i ++) {
				Load load = loads.get(i);
				if (load.process_date < expired_time) {
					count --;
					total_ms -= load.process_time;
					loads.remove(i);
					i --;
					continue;
				}
				break;
			}
			// 添加新的load
			count ++;
			total_ms += new_load.process_time;
			loads.add(new_load);
		}
	}

	public double load() {
		synchronized (this) {
			if (count == 0) {
				return 0;
			}
			return Double.parseDouble(df.format(total_ms/(count*1000)));
		}
	}
	
	public int qps() {
		synchronized (this) {
			return (int) (count * 1000 / time_interal);
		}
	}
}
